package com.starlight.flower_server.domain.service.authentication;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.starlight.flower_server.infrastructure.entity.FlowerUser;
import com.starlight.flower_server.infrastructure.entity.FlowerUserRole;
import com.starlight.flower_server.infrastructure.entity.Role;
import com.starlight.flower_server.infrastructure.mapper.FlowerUserMapper;
import com.starlight.flower_server.infrastructure.mapper.FlowerUserRoleMapper;
import com.starlight.flower_server.infrastructure.mapper.RoleMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author yfy2001
 * @date 2023/4/11 15:47
 */
@Service
public class AuthenticationService implements UserDetailsService {

    @Resource
    FlowerUserRoleMapper flowerUserRoleMapper;

    @Resource
    FlowerUserMapper flowerUserMapper;

    @Resource
    RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username==null){
            throw new UsernameNotFoundException("用户名不能为空");
        }
        FlowerUser flowerUser=flowerUserMapper.selectOne(new LambdaQueryWrapper<FlowerUser>()
               .eq(FlowerUser::getUsername,username));
        if(flowerUser==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        FlowerUserRole flowerUserRole=flowerUserRoleMapper.selectOne(new LambdaQueryWrapper<FlowerUserRole>()
                .eq(FlowerUserRole::getFlowerUserId,flowerUser.getId())
        );
        Role role=roleMapper.selectById(flowerUserRole.getRoleId());
        return User
                .withUsername(flowerUser.getUsername())
                .password(flowerUser.getPassword())
                .roles(role.getRole())
                .build();
    }
}
